const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const alumniRoutes = require('../routes/alumniRoutes');
const app = express();

// JWT配置
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'your_jwt_secret'
};

passport.use(new JwtStrategy(jwtOptions, (jwtPayload, done) => {
  const user = { id: jwtPayload.id };
  return done(null, user);
}));

// 配置 CORS
app.use(cors());
app.use(bodyParser.json());
app.use('/api/alumni', alumniRoutes);
// 创建数据库连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'alumni_job'
});

// 测试连接
pool.getConnection((err, connection) => {
    if (err) {
        console.error('数据库连接失败:', err);
        return;
    }
    console.log('数据库连接成功');
    connection.release();
});

// 根路由 - 测试用
app.get('/', (req, res) => {
    res.json({ message: 'Welcome to Alumni Job API' });
});

// 测试路由
app.get('/test', (req, res) => {
    res.json({ message: 'API is working!' });
});

// 获取所有岗位
app.get('/api/jobs', (req, res) => {
  const { status, keyword, skills, userId, role } = req.query;
  let query = '';
  const params = [];

  if (role === 'company') {
      query += 'SELECT * FROM jobs WHERE user_id = ?';
      params.push(userId);
  } else if (role === 'student' || role === 'alumni') {
      query += 'SELECT * FROM jobs WHERE status = "open"';
  } else {
      return res.status(400).json({ error: 'Invalid role' });
  }

  if (status && (role === 'student' || role === 'alumni')) {
      query += ' AND status = ?';
      params.push(status);
  }
  if (keyword) {
      query += ' AND (title LIKE ? OR company LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
  }
  if (skills) {
      query += ' AND skills LIKE ?';
      params.push(`%${skills}%`);
  }

  console.log('Executing SQL:', query);
  console.log('With params:', params);

  pool.query(query, params, (error, results) => {
      if (error) {
          console.error('数据库查询错误:', error);
          return res.status(500).json({ error: '数据库查询失败' });
      }
      console.log('Query result:', results);
      res.json(results);
  });
});

// 获取特定岗位详情
app.get('/api/jobs/:id', (req, res) => {
  const { id } = req.params;
  const query = 'SELECT * FROM jobs WHERE id = ?';

  console.log('Getting job details for ID:', id);

  pool.query(query, [id], (error, results) => {
      if (error) {
          console.error('数据库查询错误:', error);
          return res.status(500).json({ error: '数据库查询失败' });
      }
      if (results.length > 0) {
          console.log('Job details retrieved:', results[0]);
          res.json(results[0]);
      } else {
          console.log('Job not found for ID:', id);
          res.status(404).json({ error: '未找到请求的资源' });
      }
  });
});

// 获取校友列表
app.get('/api/alumni', async (req, res) => {
  const { keyword, industry } = req.query;

  // 假设这是你的数据库查询逻辑
  let alumni = await db.findAlumni({
    keyword,
    industry
  });

  // 给每个校友对象添加 hasAlumniInCompany 字段
  alumni = alumni.map(async (alumniItem) => {
    const hasAlumniInCompany = await db.checkIfOtherAlumniInCompany(alumniItem.company);
    return {
      ...alumniItem,
      hasAlumniInCompany
    };
  });

  // 使用 Promise.all 来并行处理所有异步操作
  alumni = await Promise.all(alumni);

  res.json({
    success: true,
    alumni
  });
});

// 获取站内信列表
app.get('/api/messages', (req, res) => {
    const { userId, type } = req.query;
    let query = 'SELECT * FROM messages WHERE 1=1';
    const params = [];

    if (userId) {
        query += type === 'sent' ? ' AND sender_id = ?' : ' AND receiver_id = ?';
        params.push(userId);
    }

    console.log('Executing SQL:', query);
    console.log('With params:', params);

    pool.query(query, params, (error, results) => {
        if (error) {
            console.error(error);
            return res.status(500).send('Internal Server Error');
        }
        console.log('Query result:', results);
        res.json(results);
    });
});

// 发布岗位
app.post('/api/jobs', (req, res) => {
  const { title, company, position, description, requirements, skills, status, user_id } = req.body;
  
  if (!user_id) {
      return res.status(400).json({ error: '用户ID不能为空' });
  }

  const sql = 'INSERT INTO jobs (title, company, position, description, requirements, skills, status, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
  
  console.log('Posting job with data:', {
      title,
      company,
      position,
      description,
      requirements,
      skills,
      status,
      user_id
  });

  pool.query(sql, [title, company, position, description, requirements, skills, status, user_id], (error, results) => {
      if (error) {
          console.error('发布岗位失败:', error);
          return res.status(500).json({ error: '发布岗位失败' });
      }

      const jobId = results.insertId;
      console.log('Job posted successfully with ID:', jobId);

      // 检查订阅匹配并发送通知
      const matchQuery = `
          SELECT js.*, u.id as receiver_id
          FROM job_subscriptions js 
          JOIN users u ON js.user_id = u.id 
          WHERE 
              (js.keywords IS NOT NULL AND ? LIKE CONCAT('%', js.keywords, '%'))
              OR 
              (js.skills IS NOT NULL AND ? LIKE CONCAT('%', js.skills, '%'))
      `;

      pool.query(matchQuery, [title, skills], (error, subscriptions) => {
          if (error) {
              console.error('检查订阅匹配失败:', error);
              return res.status(500).json({ error: '发布岗位成功但通知发送失败' });
          }

          console.log('Matching subscriptions:', subscriptions);

          // 为每个匹配的订阅发送通知
          const notifications = subscriptions.map(sub => {
              const content = `有新的岗位匹配您的订阅条件！\n` +
                            `岗位标题：${title}\n` +
                            `公司：${company}\n` +
                            `技能要求：${skills}\n` +
                            `点击查看详情`;

              return new Promise((resolve, reject) => {
                  const notifySql = 'INSERT INTO messages (sender_id, receiver_id, content, type, status) VALUES (?, ?, ?, ?, ?)';
                  pool.query(notifySql, [user_id, sub.user_id, content, 'system', 'unread'], (error) => {
                      if (error) {
                          console.error('发送通知失败:', error);
                          reject(error);
                      } else {
                          resolve();
                      }
                  });
              });
          });

          Promise.all(notifications)
              .then(() => {
                  res.status(201).json({ 
                      success: true,
                      message: '岗位发布成功并已发送通知', 
                      insertId: jobId 
                  });
              })
              .catch((error) => {
                  console.error('部分通知发送失败:', error);
                  res.status(201).json({ 
                      success: true,
                      message: '岗位发布成功但部分通知发送失败', 
                      insertId: jobId 
                  });
              });
      });
  });
});


async function matchAndNotifySubscriptions(job) {
  // 获取所有订阅
  const subscriptions = await Subscription.getByUserId();

  for (let subscription of subscriptions) {
      if (matches(subscription, job)) {
          // 发送站内信通知
          await sendNotification(subscription.user_id, `New job matches your subscription: ${job.title}`);
      }
  }
}

function matches(subscription, job) {
  // 简单的匹配逻辑，可以根据需求调整
  return (subscription.keywords.split(',').some(kw => job.skills.includes(kw)) ||
          subscription.skills.split(',').some(skill => job.skills.includes(skill)));
}

async function sendNotification(userId, message) {
  const query = 'INSERT INTO messages (sender_id, receiver_id, content, status) VALUES (?, ?, ?, "unread")';
  return new Promise((resolve, reject) => {
      pool.query(query, [0, userId, message], (error, results) => {
          if (error) return reject(error);
          resolve(results.insertId);
      });
  });
}

// 发送站内信
app.post('/api/messages', (req, res) => {
    const { sender_id, receiver_id, content } = req.body;
    const sql = 'INSERT INTO messages (sender_id, receiver_id, content, status) VALUES (?, ?, ?, "unread")';
    
    console.log('Sending message:', { sender_id, receiver_id, content });

    pool.query(sql, [sender_id, receiver_id, content], (error, results) => {
        if (error) {
            console.error(error);
            return res.status(500).send('Database error');
        }
        console.log('Message sent:', results.insertId);
        res.status(201).json({ message: 'Message sent successfully', insertId: results.insertId });
    });
});

// 更新岗位状态
app.put('/api/jobs/:id', (req, res) => {
    const { id } = req.params;
    const { status } = req.body;
    const sql = 'UPDATE jobs SET status = ? WHERE id = ?';
    
    console.log('Updating job status:', { id, status });

    pool.query(sql, [status, id], (error, results) => {
        if (error) {
            console.error(error);
            return res.status(500).send('Database error');
        }
        console.log('Job status updated:', results.affectedRows);
        res.json({ message: 'Job status updated successfully' });
    });
});

// 用户登录
app.post('/api/login', (req, res) => {
    const { username, password } = req.body;
    const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
    
    console.log('Logging in user:', { username });

    pool.query(query, [username, password], (error, results) => {
        if (error) {
            console.error('登录错误:', error);
            return res.status(500).json({ error: '服务器错误' });
        }
        
        if (results.length > 0) {
            const user = results[0];
            // 不返回密码
            delete user.password;
            console.log('User logged in:', user);
            res.json({ success: true, user });
        } else {
            console.log('Login failed for user:', username);
            res.status(401).json({ success: false, message: '用户名或密码错误' });
        }
    });
});

// 获取用户信息
app.get('/api/users/:id', (req, res) => {
    const { id } = req.params;
    const query = 'SELECT id, username, role, created_at FROM users WHERE id = ?';
    
    console.log('Getting user info for ID:', id);

    pool.query(query, [id], (error, results) => {
        if (error) {
            console.error('Error getting user info:', error);
            return res.status(500).json({ error: '服务器错误' });
        }
        if (results.length > 0) {
            console.log('User info retrieved:', results[0]);
            res.json(results[0]);
        } else {
            console.log('User not found for ID:', id);
            res.status(404).json({ error: '用户不存在' });
        }
    });
});

// 更新用户角色
app.put('/api/users/:id/role', (req, res) => {
    const { id } = req.params;
    const { role } = req.body;
    const query = 'UPDATE users SET role = ? WHERE id = ?';
    
    console.log('Updating user role:', { id, role });

    pool.query(query, [role, id], (error) => {
        if (error) {
            console.error('Error updating user role:', error);
            return res.status(500).json({ error: '服务器错误' });
        }
        console.log('User role updated successfully');
        res.json({ success: true });
    });
});

// 获取用户的岗位订阅
app.get('/api/users/:id/subscriptions', (req, res) => {
  const { id } = req.params;
  const query = 'SELECT * FROM job_subscriptions WHERE user_id = ?';

  console.log('Getting subscriptions for user ID:', id);

  pool.query(query, [id], (error, results) => {
      if (error) {
          console.error('Error getting subscriptions:', error);
          return res.status(500).json({ error: '服务器错误' });
      }
      console.log('Subscriptions retrieved:', results);
      res.json(results);
  });
});

// 添加岗位订阅
app.post('/api/users/:id/subscriptions', (req, res) => {
  const { id } = req.params;
  const { keywords, skills } = req.body;
  const query = 'INSERT INTO job_subscriptions (user_id, keywords, skills) VALUES (?, ?, ?)';

  console.log('Adding subscription for user ID:', { id, keywords, skills });

  pool.query(query, [id, keywords, skills], (error, results) => {
      if (error) {
          console.error('Error adding subscription:', error);
          return res.status(500).json({ error: '服务器错误' });
      }
      console.log('Subscription added:', results.insertId);
      res.status(201).json({ success: true, id: results.insertId });
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: '服务器内部错误' });
});

// 处理 404 错误
app.use((req, res) => {
    res.status(404).json({ error: '未找到请求的资源' });
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});